import netCDF4 as nc
import numpy as np

from log_own import logger


def generate_new_nc_file(variables, nc_save_path):
    """
    :param variables: 变量字典
    :param nc_save_path: nc文件存储路径
    :return: nc_save_path
    """
    height = variables['latitude']['array'].shape[0]
    width = variables['longitude']['array'].shape[0]
    # 创建nc文件
    with nc.Dataset(nc_save_path, 'w') as f_w:
        # 维度
        f_w.createDimension('latitude', height)
        f_w.createDimension('longitude', width)
        f_w.createDimension('time', np.array(variables['time']['array']).shape[0])
        # 创建变量
        for key in variables:
            if key in ['latitude', 'longitude']:
                f_w.createVariable(key, np.float64, key, fill_value=variables[key]['nodata'])
                f_w.variables[key][:] = np.array([variables[key]['array']])
        f_w.createVariable('time', np.int64, 'time')
        f_w.variables['time'][:] = variables['time']['array']
        f_w.variables['time'].units = variables['time']['units']
        # 变量写入数值和单位
        for key in variables:
            if key not in ['latitude', 'longitude', 'time']:
                f_w.createVariable(variables[key]['real_name'],
                                   np.float32,
                                   ('time', 'latitude', 'longitude'),
                                   fill_value=variables[key]['nodata'],
                                   zlib=True,
                                   complevel=3,
                                   least_significant_digit=3
                                   )
                f_w.variables[variables[key]['real_name']][:] = np.array(variables[key]['array'])
    logger.info("已生成" + nc_save_path)
    return nc_save_path
